"""
Pytest配置和共享fixtures
"""
import pytest
from typing import AsyncGenerator
from motor.motor_asyncio import AsyncIOMotorDatabase
from fastapi.testclient import TestClient
from httpx import AsyncClient
import asyncio

from app.main import app
from app.core.database import get_db
from app.core.config import settings


@pytest.fixture(scope="session")
def event_loop():
    """创建事件循环"""
    loop = asyncio.get_event_loop_policy().new_event_loop()
    yield loop
    loop.close()


@pytest.fixture
async def db() -> AsyncGenerator[AsyncIOMotorDatabase, None]:
    """
    测试数据库fixture
    使用测试数据库
    """
    from app.core.database import get_database
    test_db = await get_database()
    yield test_db
    # 清理测试数据（可选）
    # await test_db.client.drop_database(settings.MONGODB_DB_NAME + "_test")


@pytest.fixture
def client() -> TestClient:
    """创建测试客户端"""
    return TestClient(app)


@pytest.fixture
async def async_client() -> AsyncGenerator[AsyncClient, None]:
    """创建异步测试客户端"""
    async with AsyncClient(app=app, base_url="http://test") as ac:
        yield ac


@pytest.fixture
async def test_user(db: AsyncIOMotorDatabase) -> dict:
    """
    创建测试用户
    """
    from app.core.security import get_password_hash
    from bson import ObjectId
    from datetime import datetime
    
    user_data = {
        "_id": ObjectId(),
        "username": "testuser",
        "email": "test@example.com",
        "name": "Test User",
        "hashed_password": get_password_hash("testpassword123"),
        "status": "active",
        "is_verified": True,
        "roles": [],
        "permissions": [],
        "created_at": datetime.utcnow(),
        "updated_at": datetime.utcnow()
    }
    
    await db.users.insert_one(user_data)
    
    yield {
        "user_id": str(user_data["_id"]),
        "username": user_data["username"],
        "email": user_data["email"],
        "name": user_data["name"]
    }
    
    # 清理
    await db.users.delete_one({"_id": user_data["_id"]})


@pytest.fixture
async def auth_headers(async_client: AsyncClient, test_user: dict) -> dict:
    """
    获取认证头
    """
    from app.core.security import create_access_token
    
    token = create_access_token(data={"sub": test_user["user_id"]})
    return {"Authorization": f"Bearer {token}"}

